//
//  ChafenWithMenuViewController.m
//  JiaoWuGuanLi
//
//  Created by Zinzie on 14-3-26.
//  Copyright (c) 2014年 Zinzie. All rights reserved.
//

#import "ChafenWithMenuViewController.h"
#import "DataModel.h"
#import "DataModelController.h"
#import "ChafenDetailViewController.h"
#import "MainInterfaceAppDelegate.h"
#import "Score.h"
#import "CoreData+MagicalRecord.h"
#import "JDStatusBarNotification.h"
#import "CustomIOS7AlertView.h"
#import "TFHpple.h"

@interface ChafenWithMenuViewController ()<CustomIOS7AlertViewDelegate,UITextFieldDelegate>
{
    BOOL isRefreshing;
    BOOL online;
    BOOL scrollingToZero;
}
@property (weak, nonatomic) IBOutlet UIView *hideview;
@property (strong,nonatomic) NSString *year1;
@property (strong,nonatomic) NSString *year2;
@property (strong,nonatomic) NSString *year3;
@property (strong,nonatomic) NSString *year4;
@property (weak, nonatomic) IBOutlet UIButton *yearButton1;
@property (weak, nonatomic) IBOutlet UIButton *yearButton2;
@property (weak, nonatomic) IBOutlet UIButton *yearButton3;
@property (weak, nonatomic) IBOutlet UIButton *yearButton4;
@property (strong ,nonatomic) UITextField *yanZhengtext;
@property (strong ,nonatomic) UIImageView *yanZhengImg;
@property (strong ,nonatomic) CustomIOS7AlertView *alertView;


@property (strong ,nonatomic) UIView *segView;
@property (strong ,nonatomic) UISegmentedControl *segmentedControl;


@end

@implementation ChafenWithMenuViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)setDengLuXueHao:(NSString *)dengLuXueHao{
    _dengLuXueHao = dengLuXueHao;
    if (_dengLuXueHao!=nil) {
        self.leftNoDisplay.title = _dengLuXueHao;
    }
    else{
        self.leftNoDisplay.title = @"未登录";
    }
    
}

-(UIBarButtonItem *)leftNoDisplay{
    if (!_leftNoDisplay) {
        _leftNoDisplay = [[UIBarButtonItem alloc]initWithTitle:@"未登录" style:UIBarButtonItemStyleBordered target:self action:@selector(noDisplay)];
        //        self.navigationItem.leftBarButtonItem = _leftNoDisplay;
        
    }
    return _leftNoDisplay;
}

-(void)noDisplay{
    
}

- (void)viewDidLoad
{


    [super viewDidLoad];
    scrollingToZero = NO;
    self.hideview.alpha = 0;
    isRefreshing = NO;
    self.dataModelController=[[DataModelController alloc]init];
    self.scrollView.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endRefresh) name:@"ShuXinScoreOK" object:self.dataModelController];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"学期" style:UIBarButtonItemStyleBordered target:self action:@selector(menu)];
    self.navigationItem.rightBarButtonItem = right;
    self.navigationItem.leftBarButtonItem = self.leftNoDisplay;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
;
    self.navigationItem.title =  @"历年";


    

	// Do any additional setup after loading the view.
}

-(void)getYears{    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString *yearString = [myDelegate.XueHao substringToIndex:2];
    int i =[yearString intValue];
    NSString *defString = @"20aa-20bb";
    self.year1 = [defString stringByReplacingOccurrencesOfString:@"aa" withString:[NSString stringWithFormat:@"%d",i]];
    i++;
    self.year1 = [self.year1 stringByReplacingOccurrencesOfString:@"bb" withString:[NSString stringWithFormat:@"%d",i]];
    [self.yearButton1 setTitle:[NSString stringWithFormat:@"大一  %@",self.year1] forState:UIControlStateNormal];
    

    self.year2 = [defString stringByReplacingOccurrencesOfString:@"aa" withString:[NSString stringWithFormat:@"%d",i]];
    i++;
    self.year2 = [self.year2 stringByReplacingOccurrencesOfString:@"bb" withString:[NSString stringWithFormat:@"%d",i]];
    [self.yearButton2 setTitle:[NSString stringWithFormat:@"大二  %@",self.year2] forState:UIControlStateNormal];


    self.year3 = [defString stringByReplacingOccurrencesOfString:@"aa" withString:[NSString stringWithFormat:@"%d",i]];
    i++;
    self.year3 = [self.year3 stringByReplacingOccurrencesOfString:@"bb" withString:[NSString stringWithFormat:@"%d",i]];
    [self.yearButton3 setTitle:[NSString stringWithFormat:@"大三  %@",self.year3] forState:UIControlStateNormal];


    self.year4 = [defString stringByReplacingOccurrencesOfString:@"aa" withString:[NSString stringWithFormat:@"%d",i]];
    i++;
    self.year4 = [self.year4 stringByReplacingOccurrencesOfString:@"bb" withString:[NSString stringWithFormat:@"%d",i]];
    [self.yearButton4 setTitle:[NSString stringWithFormat:@"大四  %@",self.year4] forState:UIControlStateNormal];

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    //[self.scrollView setContentSize:CGSizeMake(320, 540)];
    [self becomeFirstResponder];
    //[self.notification displayNotificationWithMessage:@"test1234" completion:nil];

    //segmentedControl 配置
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:[@[@"大一",@"上",@"下"] mutableCopy]];
    self.segView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
    [self.segView addSubview:self.segmentedControl];
    self.segmentedControl.frame = CGRectMake(35, 35, 150, 30);
    self.segmentedControl.selectedSegmentIndex = 0;
    //self.navigationItem.titleView = nil;
    [self.segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    //刷新配置
    [JDStatusBarNotification setDefaultStyle:^JDStatusBarStyle *(JDStatusBarStyle *style) {
        style.barColor = [UIColor colorWithRed:0.180 green:0.466 blue:0.890 alpha:1.000];
        style.textColor = [UIColor whiteColor];
        return style;
    }];
    //是否在线
    online = [[[NSUserDefaults standardUserDefaults] objectForKey:@"online"] boolValue];
    if (!online) {
        [self setupAlertView];
    }
    
    //check是否需要刷新
    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    self.dengLuXueHao = myDelegate.userName;
    NSPredicate *predicateByStudentNumber = [NSPredicate predicateWithFormat:@"ofWho.xueHao == %@",myDelegate.XueHao];
    if ([Score MR_findAllWithPredicate:predicateByStudentNumber].count==0) {
        if(!online){
            [self showAlert];
            
        }else{
        [self refreshScore];
        }
    }
    //获取菜单年份
     [self getYears];
}


-(void)viewDidDisappear:(BOOL)animated{
    [self resignFirstResponder];
    [super viewDidDisappear:animated];
    [JDStatusBarNotification dismiss];
    isRefreshing = NO;
    //self.hideview.hidden = YES;
    [self hideMenu];
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"ShuXinScoreOK" object:self.dataModelController];

}

- (void)beginRefreshingTableView {
    [self.refresh beginRefreshing];
        if (self.tableView.contentOffset.y == 0) {
        
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
            
            self.tableView.contentOffset = CGPointMake(0, -self.refresh.frame.size.height);
            
        } completion:^(BOOL finished){
            [self refreshScore];

        }];

        
    }

}
-(void)refreshScore{
    [JDStatusBarNotification showWithStatus:@"成绩更新中" dismissAfter:8];
    [self.dataModelController refreshModal];
    NSLog(@"start refresh");
    //[self.refresh beginRefreshing];

}
-(void)endRefresh{
    online = [[[NSUserDefaults standardUserDefaults] objectForKey:@"online"] boolValue];
    NSLog(@"endRefreshing");
    [JDStatusBarNotification dismissAnimated:YES];
    [self performSelector:@selector(showEndRefreshNotification) withObject:self afterDelay:0.5f];
}

-(void)showEndRefreshNotification{
    NSLog(@"show notification");
    if (self.dataModelController.loginWrong) {
        [JDStatusBarNotification showWithStatus:@"验证码错误" dismissAfter:1.5f];
    }else if (self.dataModelController.refreshError) {
        [JDStatusBarNotification showWithStatus:@"更新失败,请检查网络" dismissAfter:1.5f];
    }else if (self.dataModelController.haveNewData==YES) {
        [JDStatusBarNotification showWithStatus:@"更新完成" dismissAfter:1.5f];

        [self.tableView reloadData];
    }else{
        [JDStatusBarNotification showWithStatus:@"更新完成,无新成绩" dismissAfter:1.5f];
    }
    isRefreshing = NO;

}
- (IBAction)buttonTouched:(UIButton *)sender {
    NSLog(@"touched");
    if ([sender.currentTitle hasPrefix:@"大四"]) {
        self.dataModelController.scoreOfYear=self.year4;
        self.dataModelController.termOfYear=nil;
        [self.segmentedControl setTitle:@"大四" forSegmentAtIndex:0];
        self.segmentedControl.selectedSegmentIndex = 0;
        self.navigationItem.titleView = self.segView;
        
        
    }else if ([sender.currentTitle hasPrefix:@"大三"]) {
        self.dataModelController.scoreOfYear=self.year3;
        self.dataModelController.termOfYear=nil;
        [self.segmentedControl setTitle:@"大三" forSegmentAtIndex:0];
        self.segmentedControl.selectedSegmentIndex = 0;
        self.navigationItem.titleView = self.segView;


    }else if ([sender.currentTitle hasPrefix:@"大二"]) {
        self.dataModelController.scoreOfYear=self.year2;
        self.dataModelController.termOfYear=nil;
        [self.segmentedControl setTitle:@"大二" forSegmentAtIndex:0];
        self.segmentedControl.selectedSegmentIndex = 0;
        self.navigationItem.titleView = self.segView;


    }else if ([sender.currentTitle hasPrefix:@"大一"]){
        self.dataModelController.scoreOfYear=self.year1;
        self.dataModelController.termOfYear=nil;
        [self.segmentedControl setTitle:@"大一" forSegmentAtIndex:0];
        self.segmentedControl.selectedSegmentIndex = 0;
        self.navigationItem.titleView = self.segView;

    }else if ([sender.currentTitle isEqualToString:@"历年"]){
        self.dataModelController.scoreOfYear=nil;
        self.dataModelController.termOfYear=nil;
        self.navigationItem.title = @"历年";
        self.navigationItem.titleView = nil;



    }
    //scrollingToZero = YES;
   // [self performSelector:@selector(changeYearStep2) withObject:nil afterDelay:2];
    if(self.tableView.contentOffset.y>1100){
        [self.tableView setContentOffset:CGPointZero animated:NO];
    }else{
        [self.tableView setContentOffset:CGPointZero animated:YES];
    }
    [self.tableView reloadData];
    [self menu];
}

-(void)segmentedControlAction:(UISegmentedControl *)sender{
    if ([[sender titleForSegmentAtIndex:0] isEqualToString:@"大一"]) {
        [self termSelectForYear1:sender];
    }
    else if ([[sender titleForSegmentAtIndex:0] isEqualToString:@"大二"]){
        [self termSelectForYear2:sender];
    }else if ([[sender titleForSegmentAtIndex:0] isEqualToString:@"大三"]){
        [self termSelectForYear3:sender];
    }else if ([[sender titleForSegmentAtIndex:0] isEqualToString:@"大四"]){
        [self termSelectForYear4:sender];
    }


}
- (IBAction)termSelectForYear1:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 1:
            self.dataModelController.scoreOfYear=self.year1;
            self.dataModelController.termOfYear=@"1";
            break;
            
        case 2:
            self.dataModelController.scoreOfYear=self.year1;
            self.dataModelController.termOfYear=@"2";
            break;
            
        default:
            self.dataModelController.scoreOfYear=self.year1;
            self.dataModelController.termOfYear=nil;
            break;
    }
    [self changeYearStep1];
    
}
- (IBAction)termSelectForYear2:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 1:
            self.dataModelController.scoreOfYear=self.year2;
            self.dataModelController.termOfYear=@"1";
            break;
            
        case 2:
            self.dataModelController.scoreOfYear=self.year2;
            self.dataModelController.termOfYear=@"2";
            break;
            
        default:
            self.dataModelController.scoreOfYear=self.year2;
            self.dataModelController.termOfYear=nil;
            break;
    }
    [self changeYearStep1];

}
- (IBAction)termSelectForYear3:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 1:
            self.dataModelController.scoreOfYear=self.year3;
            self.dataModelController.termOfYear=@"1";
            break;
            
        case 2:
            self.dataModelController.scoreOfYear=self.year3;
            self.dataModelController.termOfYear=@"2";
            break;
            
        default:
            self.dataModelController.scoreOfYear=self.year3;
            self.dataModelController.termOfYear=nil;
            break;
    }
    [self changeYearStep1];

}
- (IBAction)termSelectForYear4:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 1:
            self.dataModelController.scoreOfYear=self.year4;
            self.dataModelController.termOfYear=@"1";
            break;
            
        case 2:
            self.dataModelController.scoreOfYear=self.year4;
            self.dataModelController.termOfYear=@"2";
            break;
            
        default:
            self.dataModelController.scoreOfYear=self.year4;
            self.dataModelController.termOfYear=nil;
            break;
    }
    [self changeYearStep1];

}

-(void)changeYearStep1{
    scrollingToZero = YES;
    [self.tableView reloadData];
    [self.tableView setContentOffset:CGPointZero animated:NO];
    NSLog(@"fuck fuck %hhd",scrollingToZero);
    [self performSelector:@selector(changeYearStep2) withObject:nil afterDelay:2];
}

-(void)changeYearStep2{
    scrollingToZero = NO;
}

#pragma mark - handle menu

-(void)menu{
    if (self.scrollView.hidden) {
        [self showMenu];
    }
    else {
        [self hideMenu];
    }

}


- (void) hideMenu {
    // Set new origin of menu
    CGRect menuFrame = self.scrollView.frame;
    //CGRect tableFrame = self.tableView.frame;
    if ([[UIScreen mainScreen] bounds].size.height!=568) {
        self.tabBarController.tabBar.hidden=NO;
    }
   // [self.tableView setContentOffset:CGPointZero animated:YES];

    //CGFloat navigationBarHeight = 60;
    //tableFrame.origin.y = navigationBarHeight;
    menuFrame.origin.y = -368; //navigationBarHeight - self.scrollView.frame.size.height;
    
    [UIView animateWithDuration:0.30f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.scrollView.frame = menuFrame;
                         //self.tableView.frame = tableFrame;
                     }
                     completion:^(BOOL finished){
                         self.scrollView.hidden = YES;
                         //[self.tableView setContentOffset:CGPointZero animated:YES];
                         [UIView animateWithDuration:0.30f
                                               delay:0
                                             options:UIViewAnimationOptionCurveEaseInOut
                                          animations:^{
                                              self.hideview.alpha = 0;
                                          }
                                          completion:^(BOOL finished){
                                              self.hideview.hidden = YES;
                                          }];

                     }];
    
}

-(void)showMenu{
    self.hideview.hidden = NO;
    self.scrollView.hidden =NO;
    if ([[UIScreen mainScreen] bounds].size.height!=568) {
        self.tabBarController.tabBar.hidden=YES;
    }
    CGRect menuFrame = self.scrollView.frame;
    //CGRect tableFrame = self.tableView.frame;
    //tableFrame.origin.y = self.scrollView.frame.size.height + self.tableView.frame.origin.y;
    CGFloat navigationBarHeight = 60;
    menuFrame.origin.y = navigationBarHeight;
    [UIView animateWithDuration:0.30f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.scrollView.frame = menuFrame;
                         //self.tableView.frame = tableFrame;
                     }
                     completion:^(BOOL finished){
                         [UIView animateWithDuration:0.30f
                                               delay:0
                                             options:UIViewAnimationOptionCurveEaseInOut
                                          animations:^{
                                              self.hideview.alpha = 1;
                                          }
                                          completion:^(BOOL finished){
                                          }];
                     }];
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.dataModelController countOfChengJiList]+2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        
        NSLog(@"加权 loading");
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"standardGPACell"];
        UILabel *label = (UILabel *)[cell viewWithTag:1];
        if ([self.dataModelController.standardGPA isEqualToString:@"nan"]) {
            label.text = @"0" ;
        }
        else{
        label.text = self.dataModelController.standardGPA;
        }
        return  cell;
        
    }else if (indexPath.row==1){
        NSLog(@"standard gpa loading");
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fourGPACell"];
        UILabel *label = (UILabel *)[cell viewWithTag:1];
        if ([self.dataModelController.standardGPA isEqualToString:@"nan"]) {
            label.text = @"0" ;
        }
        else{
            label.text = self.dataModelController.fourGPA;
        }
        return  cell;

        
    }
    else{
    static NSString *CellIdentifier = @"ModelCells";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    DataModel *dataAtIndex = [self.dataModelController objectInChengJiListAtIndex:indexPath.row-2];
        NSLog(@"name of class is %@",dataAtIndex.name);
    
    UILabel *label = (UILabel *)[cell viewWithTag:1];
    label.text = dataAtIndex.name;
    label = (UILabel *)[cell viewWithTag:2];
    label.text = dataAtIndex.mark;
    label = (UILabel *)[cell viewWithTag:3];
    label.text = dataAtIndex.attribute;
    label = (UILabel *)[cell viewWithTag:4];
    label.text = dataAtIndex.jidian;
    
    
    /*    [[cell textLabel] setText:dataAtIndex.name];
     [[cell detailTextLabel] setText:dataAtIndex.mark];
     */
    return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier]isEqualToString:@"DetailPush"]) {
        
        ChafenDetailViewController *detailViewController = [segue destinationViewController];
        detailViewController.data = [self.dataModelController objectInChengJiListAtIndex:[self.tableView indexPathForSelectedRow].row-2];
        [segue.destinationViewController setHidesBottomBarWhenPushed:YES];
    }
}

#pragma mark - Shake to menu
/*
 摇动设备呼出学期菜单
 */
-(BOOL)canBecomeFirstResponder{
    return YES;
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (event.subtype == UIEventSubtypeMotionShake) {
        [self menu];
    }
}
#pragma mark - Pull to Refresh

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"offsetis %f",scrollView.contentOffset.y);
    if (scrollView==self.tableView && scrollView.contentOffset.y<-80) {
        NSLog(@"fuck fuck fuck %hhd",scrollingToZero);
        if (isRefreshing==NO) {
            isRefreshing = YES;
            int i = 0;
            if (online) {
                    [self refreshScore];
                i++;
            }else{
                
                [self showAlert];
                i++;
                
            }
            NSLog(@"i is %d",i);

        }
        
    }
}
#pragma mark - handle alert

-(void)showAlert{
    if (self.dataModelController.loginWrong) {
        self.alertView.containerView.frame = CGRectMake(0, 0, 250, 135);
        UILabel *notice = [[UILabel alloc]initWithFrame:CGRectMake(30, 97, 195, 40)];
        notice.text = @"若教务系统密码更改,请在\"更多\"中\n  清除当前学生数据,并重新登录";
        notice.font = [UIFont fontWithName:@"STHeitiJ-Light" size:13];
        notice.numberOfLines = 2;
        notice.textColor = [UIColor colorWithWhite:0.495 alpha:1.000];
        [self.alertView.containerView addSubview:notice];
    }
    [self.alertView show];
    [self shuaXinYanZhengMa];
    [self performSelector:@selector(keyboardAppear) withObject:self afterDelay:0.1];
    
    //[self.yanZhengtext becomeFirstResponder];

}

-(void)keyboardAppear{
    [self.yanZhengtext becomeFirstResponder];
}

-(void)setupAlertView{
    self.alertView = [[CustomIOS7AlertView alloc] init];//弹出alert输入验证码登录.
    [self.alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确定", @"取消", nil]];
    [self.alertView setContainerView:[self alertViewCustom]];
    [self.alertView setDelegate:self];
    [self.alertView setUseMotionEffects:false];
}

-(UIView *)alertViewCustom{
    UIView *alertViewContent = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 250, 105)];
    alertViewContent.backgroundColor = [UIColor clearColor];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(73, 7, 180, 20)];
    title.text = @"请输入验证码";
    title.textColor = [UIColor colorWithWhite:0.395 alpha:1.000];
    UIActivityIndicatorView *yanzhengIndi = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    yanzhengIndi.frame = CGRectMake(115, 37, 20, 20);
    yanzhengIndi.tag = 2;
    self.yanZhengImg = [[UIImageView alloc]initWithFrame:CGRectMake(89, 34, 72, 27)];
    self.yanZhengImg.tag = 1;
    self.yanZhengtext = [[UITextField alloc]initWithFrame:CGRectMake(65, 67, 120, 30)];
    self.yanZhengtext.backgroundColor  = [UIColor clearColor];
    self.yanZhengtext.borderStyle = UITextBorderStyleRoundedRect;
    self.yanZhengtext.keyboardType = UIKeyboardTypeAlphabet;
    self.yanZhengtext.autocorrectionType = UITextAutocorrectionTypeNo;
    self.yanZhengtext.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.yanZhengtext.clearButtonMode = UITextFieldViewModeNever;
    self.yanZhengtext.returnKeyType =UIReturnKeyDone;
    self.yanZhengtext.delegate = self;
    self.yanZhengImg.backgroundColor = [UIColor whiteColor];
    [alertViewContent addSubview:self.yanZhengImg];
    [alertViewContent addSubview:yanzhengIndi];
    [alertViewContent addSubview:title];
    [alertViewContent addSubview:self.yanZhengtext];
    [yanzhengIndi startAnimating];
    return alertViewContent;
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"%@",textField);
    [textField resignFirstResponder];
    [self customIOS7dialogButtonTouchUpInside:self.alertView clickedButtonAtIndex:0];
    return YES;
    
}

- (void)customIOS7dialogButtonTouchUpInside: (CustomIOS7AlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
    NSLog(@"button pressed at index %d",buttonIndex);
    if (buttonIndex==0) {
        if (self.yanZhengtext.text.length!=4) {
            [JDStatusBarNotification showWithStatus:@"验证码错误" dismissAfter:2];
            isRefreshing = NO;
        }else{
        //isRefreshing = YES;
        [JDStatusBarNotification showWithStatus:@"成绩更新中" dismissAfter:8];
        self.dataModelController.yanZheng = self.yanZhengtext.text;
        }
    }else if(buttonIndex ==1){
        isRefreshing = NO;
    }
    self.yanZhengtext.text = @"";
    [alertView close];
}

-(void)shuaXinYanZhengMa{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableURLRequest *UrlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: @"http://gdjwgl.bjut.edu.cn/CheckCode.aspx"]];
        //提交Cookie，上一行的NSURLRequest被改为NSMutableURLRequest
        
        if([AFHTTPRequestOperationManager manager].cookieDictionary) {
            [UrlRequest setHTTPShouldHandleCookies:NO];
            
            [UrlRequest setAllHTTPHeaderFields:[AFHTTPRequestOperationManager manager].cookieDictionary];
        }
        
        //end
        AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:UrlRequest];
        requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
        [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Response: %@", responseObject);
            dispatch_async(dispatch_get_main_queue(), ^{
               self.yanZhengImg.image = responseObject;
                UIActivityIndicatorView *indi = (UIActivityIndicatorView *)[self.alertView.containerView viewWithTag:2];
                indi.hidden = YES;
            });
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"无法连接网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alert show];
            NSLog(@"fail");
            
        }];
        [requestOperation start];
        
        // 显示验证码
    });
    
    
}
@end
